import cv2
from utils.common import load_image, show_image, make_dirs  # 导入公共函数
from utils.config import exp5_silhouette_path, exp5_output_dir  # 导入输出路径

# 确保输出目录存在
make_dirs(exp5_output_dir)

# 加载图片并显示
image = load_image()
show_image("Original Image", image)

# 灰度化
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
show_image("Grayscale Image", gray_image)

# 二值化
_, binary = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY)
show_image("Binary Image", binary)

# 查找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 绘制轮廓 - Use a copy of the original image for drawing colored contours
img_with_contours = image.copy()  # Keep the original color for contour drawing
cv2.drawContours(img_with_contours, contours, -1, (0, 255, 0), 2)

# 显示并保存结果
show_image("Contours", img_with_contours)
cv2.imwrite(exp5_silhouette_path, gray_image)
print(f"轮廓提取结果已保存到：{exp5_silhouette_path}")
